// import $http from './utils/http.js';
import {
    byteToString,
    isEmpty,
    formatNullCharacter
} from './utils/utilNFC'
let util = require('./utils/util.js')


let {
    $http
} = require('./utils/http.js');
App({
    globalData: {
        // URL: 'https://emweb.easys.co/api/web/web', //正式

        sid: 18, //站点id
        openid: "", //用户openid
        getOpenidPromise: null, // 存储 Promise 对象

        judgeBigScreen: false, //判断屏幕
        img_file: '', //序列帧图片
        headheight: '', //刘海屏适配
        eDetail: null,
        userInfo: null,
        login: false,
        isIpx: false, //是否是苹果x

        height: 0,
        screenHeight: 0,
        windowWidth: 0,

        showlist: [], //打卡点列表（内total为积分）
        giftsList: [], //礼品列表数据

        // user: "", //接口返回的所有数据
        user: {
            // "id": 2,
            // "truename": "张三", //真实名称
            // "nickname": "cianyi", //昵称
            // "avatar": "https://thirdwx.qlogo.cn/mmopen/vi_32/PiajxSqBRaEIIPuqROwq5PCwW0ZAQ2Q4BiapY6jRHrDz8l6GV33HebAh4Zp0RnjibT8aBeBz2UPsBib6v0uOnW2CzjiaBah4RyVa9hNlZEkIq4CkibCLA1yAqRLA/132", //头像
            // "gender": 0, //性别：0未知，1男，2女
            // "integral": 0, //积分
            // "gold": 0 //金币
        }, //接口返回的所有数据

        screenHeight: "2vh",

        nfcInfo: {},
        arg: {},
    },
    login() {
        var that = this
        wx.showLoading({
            title: '',
        })
        // 登录
        this.globalData.getOpenidPromise = new Promise((resolve, reject) => {
            wx.login({
                success: res => {
                    // 发送 res.code 到后台换取 openId, sessionKey, unionId
                    console.log(res)
                    console.log(res.code)
                    // return
                    if (res.code) {
                        this.$http.get('/hd_project/Play/getOpenid?code=' + res.code, {}, false, 'json')
                            .then((res) => {

                                console.log(res)
                                if (res.code != 200) {
                                    wx.showModal({
                                        title: '网络不佳',
                                        content: '请点击下方按钮重新请求',
                                        complete: (res) => {
                                            if (res.cancel) {
                                                that.login()
                                            }

                                            if (res.confirm) {
                                                that.login()
                                            }
                                        }
                                    })
                                    return
                                }
                                wx.setStorageSync('openid', res.data)
                                that.globalData.openid = res.data;
                                console.log('openid = ' + wx.getStorageSync('openid'))
                                that.getUser()

                                if (that.loginCallback) {
                                    that.loginCallback();
                                }

                                resolve(res.data); // 成功时 resolve

                            })
                            .catch((error) => {
                                wx.hideLoading()
                                wx.showModal({
                                    title: '网络不佳',
                                    content: '请重新进入小程序。',
                                    complete: (res) => {
                                        if (res.cancel) {
                                            that.login()
                                        }

                                        if (res.confirm) {
                                            that.login()
                                        }
                                    }
                                })
                            })
                    } else {
                        wx.showToast({
                            title: res.errMsg,
                            icon: "none"
                        })
                        console.log('登录失败！' + res.errMsg)
                    }

                },
                fail: (err) => {
                    wx.hideLoading()
                    wx.showModal({
                        title: '网络不佳',
                        content: '请重新进入小程序。',
                        complete: (res) => {
                            if (res.cancel) {
                                that.login()
                            }

                            if (res.confirm) {
                                that.login()
                            }
                        }
                    })
                }
            })

        });
    },


    // 获取用户信息
    getUser() {
        var that = this
        // wx.showLoading()
        return new Promise(function (resolve, reject) {
            $http.get('/hd_project/Play/checkIn').then(res => {
                console.log(res)
                wx.hideLoading()
                if (res.code == '200') {

                    that.globalData.user = res.data

                    wx.setStorageSync('user', res.data)

                    console.log(that.globalData.user)

                } else {
                    // wx.showToast({
                    //   title: res.msg,
                    //   icon:"none"
                    // })
                    wx.showModal({
                        title: '网络繁忙',
                        content: res.msg,
                        complete: (res) => {
                            if (res.cancel) {
                                that.getUser()
                            }

                            if (res.confirm) {
                                that.getUser()
                            }
                        }
                    })

                }

                // if (that.getUserCallback2) {
                //   that.getUserCallback2();
                // }

                resolve(res); // 把 res 返回出去


            }).catch(error => {
                console.log(error)
                wx.hideLoading()
                wx.showModal({
                    title: '',
                    content: '网络繁忙',
                    complete: (res) => {
                        if (res.cancel) {
                            that.getUser()
                        }

                        if (res.confirm) {
                            that.getUser()
                        }
                    }
                })
            })
        })

    },

    onLaunch(options) {
        console.log(options)
        console.log("onLaunch")

        this.parseQrCodeParams(options);


        var that = this

        wx.setStorageSync('sid', this.globalData.sid)

        // 监听网络状态 如果断网提示
        wx.onNetworkStatusChange(function ({
            networkType
        }) {
            if (networkType === 'none') {

                wx.showModal({
                    title: '提示',
                    showCancel: false,
                    content: '网络不佳，请重新进入小程序。',
                    complete: (res) => {

                    }
                })
            }
        })

        // this.checkPlatform()
        // this.onInit()

        // 测试的时候关闭
        this.login()


        // wx.loadFontFace({
        //   family: 'SerifCN',
        //   source: 'url("https://easysart.oss-cn-shenzhen.aliyuncs.com/images/West/ceshi/1609493479503931.ttf")',
        //   global: true,
        //   success: function (res) {
        //     console.log('customFont loaded')
        //   },
        //   fail: function (res) {
        //     console.log(res)
        //   }
        // })

        // 360度关闭

        //下载好序列帧图片
        // wx.downloadFile({
        //   url: 'https://easysart.oss-cn-shenzhen.aliyuncs.com/yang/2023/Toyota/1023/map/1699251044216.png',
        //   success(res) {
        //     console.log(res)
        //     if (res.statusCode === 200) {
        //       console.log(res.tempFilePath, 'tupian');
        //       wx.removeStorageSync('img_file')
        //       wx.setStorageSync('img_file', res.tempFilePath)
        //     }
        //   },
        //   fail(res) {
        //     console.log(res)
        //   },
        // })
        // 360度关闭


        //获取设备顶部窗口的高度（不同设备窗口高度不一样，根据这个来设置自定义导航栏的高度）
        //这个最初我是在组件中获取，但是出现了一个问题，当第一次进入小程序时导航栏会把
        //页面内容盖住一部分,当打开调试重新进入时就没有问题
        wx.getSystemInfo({
            success: (res) => {

                let modelmes = res.model;
                // console.log(modelmes,"我是手机型号")
                if (modelmes.search('iPhone X') != -1) {
                    this.globalData.isIpx = true
                }
                let clientHeight = res.windowHeight;
                let clientWidth = res.windowWidth;
                let windowWidth = res.windowWidth;
                let ratio = 750 / clientWidth;
                let height = clientHeight * ratio;
                this.globalData.phoneHeight = height;
                // console.log(height,"我是自己算的手机高度")
                console.log("手机宽度", res.screenWidth)
                console.log("手机高度", res.screenHeight)
                this.globalData.height = res.statusBarHeight + 46;
                this.globalData.screenHeight = res.screenHeight;
                this.globalData.windowWidth = windowWidth; //缓存全局宽度用来计算fontSizes适应屏幕

                if (res.screenHeight - res.safeArea.bottom > 5) {
                    that.globalData.isIpx = true;
                } else {
                    that.globalData.isIpx = false;
                }

            }
        })
        // 监听小程序更新
        const updateManager = wx.getUpdateManager()
        updateManager.onUpdateReady(() => {
            updateManager.applyUpdate()
        })
    },
    // 解析二维码参数的方法
    parseQrCodeParams(options) {
        let fromId = 1; // 默认为1
        if(!wx.getStorageSync('from_id')){
            wx.setStorageSync('from_id', fromId);
        }

        // 判断进入场景
        const entryScene = options.scene;
        const isQrCodeEntry = this.isQrCodeScene(entryScene);


        if (isQrCodeEntry) {
            // 处理普通二维码的情况
            if (options.query && options.query.q) {

                try {
                    // 对scene参数进行解码
                    const scene = decodeURIComponent(options.query.q);
                    // 解析scene中的参数
                    const from_id = util.getParams(scene, "from_id");
                    if (from_id) {
                        fromId = from_id;
                    }
                } catch (error) {
                    console.error('解析scene参数出错:', error);
                }
            }
            // 处理太阳码的情况
            else if (options.query && options.query.from_id) {
                fromId = options.query.from_id;
            }

            // 将fromId存入缓存
            wx.setStorageSync('from_id', fromId);
            console.log('存储from_id到缓存:', fromId);
        } else {
            // 非扫码进入，不更新from_id
            console.log('非扫码进入，保留原有from_id缓存:');
        }
    },
    // 判断是否为扫码进入场景
    isQrCodeScene(scene) {
        // 常见的扫码场景值
        const qrCodeScenes = [
            1011, // 扫描二维码
            1012, // 长按识别二维码
            1013, // 手机相册选取二维码
            1047, // 扫描小程序码
            1048, // 长按识别小程序码
            1049 // 手机相册选取小程序码
        ];

        return qrCodeScenes.includes(scene);
    },


    // 全局事件中心（用于页面订阅NFC事件）
    // 确保App对象中的nfcEvent结构正确
    nfcEvent: {
        listeners: [],
        subscribe(callback) {
            if (typeof callback === 'function') {
                this.listeners.push(callback);
            }
        },
        unsubscribe(callback) {
            this.listeners = this.listeners.filter(fn => fn !== callback);
        },
        emit(data) {
            this.listeners.forEach(cb => {
                try {
                    cb(data);
                } catch (e) {
                    console.error('NFC事件监听错误', e);
                }
            });
        }
    },
    onInit() {
        const platform = this.globalData.platform

        if (platform == 'android') {
            this.NFCAdapter = wx.getNFCAdapter()
            this.NFClistener()
        } else {
            if (platform != 'devtools') {
                wx.showModal({
                    title: '提示',
                    content: '小程序NFC官方暂仅支持安卓设备',
                    confirmColor: '#d93e4b',
                    confirmText: '确定',
                    showCancel: false
                })
            }
        }
    },
    /**
     * 开始监听 NFC
     */
    // 修改NFClistener方法中的回调绑定
    NFClistener() {
        const self = this; // 保存当前上下文
        this.NFCAdapter.startDiscovery({
            success: () => {
                // 使用箭头函数保持this指向
                this.NFCAdapter.onDiscovered(res => {
                    this.discoverHandler(res); // 保持正确的this指向
                });
            },
            fail: error => {
                console.error(error)
            }
        })
    },
    checkPlatform() {
        const sys = wx.getSystemInfoSync()

        this.globalData.platform = sys.platform
        if (sys && sys.platform != 'android' && sys.platform != 'devtools') {
            this.globalData.nfcIsAvailable = false
            wx.showModal({
                title: '当前设备暂不支持NFC功能，请使用扫码体验',
                showCancel: false
            })
        }
    },
    /**
     * 监听回调
     */
    discoverHandler(callback) {
        try {
            console.log('==================== START ====================')
            console.log('onDiscovered callback=>', callback)
            if (callback.messages) {
                let cordsArray = callback.messages[0].records
                cordsArray.forEach(item => {
                    let nfcInfo = {
                        payload: formatNullCharacter(byteToString(new Uint8Array(item.payload))),
                        id: byteToString(new Uint8Array(item.id)),
                        type: byteToString(new Uint8Array(item.type))
                    }
                    // this.setData({
                    //     nfcInfo
                    // })

                    this.globalData.nfcInfo = nfcInfo
                })
            } else {
                // this.setData({
                //     nfcInfo: {}
                // })

                this.globalData.nfcInfo = {}
            }
            console.log('nfcInfo', this.globalData.nfcInfo)
            console.log(this.globalData.nfcInfo)

            let arg = this.getUrlParams(this.globalData.nfcInfo.payload)
            console.log(arg)

            this.globalData.arg = arg

            // 在解析完成后触发全局事件
            this.nfcEvent.emit({
                type: 'nfc_discovered',
                data: this.globalData.arg,
            });

            // 绑定卡
            if (arg.type == '1') {
                wx.reLaunch({
                    url: '/pages/bindingCard/bindingCard?id=' + arg.id,
                })
            }
            // 打卡
            if (arg.type == '2') {
                wx.switchTab({
                    url: '/pages/More/More',
                })
            }
            console.log('===================== END =====================')
        } catch (e) {
            console.error('NFC处理错误', e);
            this.nfcEvent.emit({
                type: 'nfc_error',
                error: "nfc报错"
            });
        }
    },
    getUrlParams(queryString) {
        // 防御性判断：确保输入是字符串
        if (typeof queryString !== 'string') {
            return {};
        }

        // 查找问号位置时增加容错
        const questionMarkIndex = queryString.indexOf('?');

        // 如果没有问号或问号在末尾(如 "en?"), 返回空对象
        if (questionMarkIndex === -1 || questionMarkIndex === queryString.length - 1) {
            return {};
        }

        // 安全截取查询部分
        const queryPart = queryString.substring(questionMarkIndex + 1);

        const params = {};
        queryPart.split('&').forEach(pair => {
            const [key, value] = pair.split('=');
            if (key && value !== undefined) {
                params[key] = decodeURIComponent(value); // 如果需要解码可以加上
            }
        });

        return params;
    },
    getSystemInfo() {
        const that = this;
        wx.getSystemInfo({
            success: function (res) {
                that.globalData.platform = res.platform
            }
        })
    },


    // 打卡或者开始游戏接口
    payError(record_id) {


        var that = this
        if (!record_id) {
            wx.showToast({
                title: '暂无轮询id',
                icon: "none"
            })
            return
        }


        // let data = {
        //   record_id: record_id,
        // }


        // $http.post('/Comics/payError', data, false, "json")
        $http.get('/Comics/payError?record_id=' + record_id).then(res => {
            console.log(res)
            if (res.code == 200) {

                wx.hideLoading()

            } else {
                wx.showToast({
                    title: res.msg,
                    icon: "none"
                })
            }

        })


    },
    // 获取项目类型名称
    getPlayTypeName(type) {
        const types = {
            1: '体验/打卡',
            2: '闯关/完成项目',
            3: '直接兑奖项目',
            4: '兑换/核销奖品',
            5: '留资项目'
        }
        return types[type] || '未知类型'
    },

    $http: $http,
    // 请求
    request(config = {
        method: 'GET',
        success: () => {},
        fail: () => {}
    }) {
        let {
            url,
            method,
            header,
            data,
            success,
            fail,
            timeout,
            dataType,
            responseType,
            complete,
        } = config;
        wx.request({
            url: url,
            method: method,
            header: header,
            timeout: timeout,
            dataType: dataType,
            responseType: responseType,
            data: {

                ...data
            },
            success: success,
            fail: fail,
            complete: complete,
        })
    },
})